<?php
//声明命名空间
namespace Admin\Model;

use \Frame\Libs\BaseModel;

// 定义最终的用户模型类
final class UserModel extends BaseModel
{
    private $table = 'users';

    // 获取所有用户数据
    public function fetchAll()
    {
        $sql = "select * from $this->table order by `id` desc";
        $rows = $this->pdo->fetchAll($sql, array());
        if(!$rows) {
            return [];
        }
        else{
            return $rows;
        }
    }
    
    // 根据ID获取用户
    public function getUserById($id){
        $sql = "select * from $this->table where id = :id";
        $params=[':id'=>$id];
        $results = $this->pdo->fetchOne($sql, $params);
        return $results;
    }

    // 更新用户信息
    public function updateUser($id,$username,$password,$email,$status){
        // 构建SQL参数
        $params=[':username' => $username, ':email' => $email, ':status' => $status, ':id' => $id];
        
        // 如果提供了密码，则更新密码
        if (!empty($password)) {
            $sql = "UPDATE $this->table SET username=:username,password=:password,email=:email,status=:status where id=:id";
            $params[':password'] = $password;
        } else {
            $sql = "UPDATE $this->table SET username=:username,email=:email,status=:status where id=:id";
        }
        
        return $this->pdo->exec($sql, $params);
    }

    // 更改用户状态
    public function changeStatus($id,$status){
        $sql = "UPDATE $this->table SET status=:status where id=:id";
        $params=[':status' => $status, ':id' => $id];
        return $this->pdo->exec($sql, $params);
    }

    // 删除单个用户
    public function deleteUser($uid){
        $sql = "DELETE FROM $this->table WHERE id=:id";
        $params=[':id' => $uid];
        return $this->pdo->exec($sql, $params);
    }
    
    // 批量删除用户
    public function batchDelete($ids){
        // 确保ids是数组或逗号分隔的字符串
        if (is_array($ids)) {
            $idList = implode(',', $ids);
        } else {
            $idList = $ids;
        }
        
        // 防止SQL注入，只允许数字和逗号
        $idList = preg_replace('/[^0-9,]/', '', $idList);
        
        $sql = "DELETE FROM $this->table WHERE id IN ($idList)";
        return $this->pdo->exec($sql);
    }
    
     //搜索用户
    public function searchUsers($keyword){
        // 转义关键词以防止SQL注入
        $searchKeyword = '%' . $this->pdo->quote($keyword) . '%';
        $searchKeyword = str_replace("'", '', $searchKeyword);

        $sql = "SELECT * FROM $this->table WHERE username LIKE :keyword OR email LIKE :keyword ORDER BY id DESC";
        $params = [':keyword' => $searchKeyword];

        $rows = $this->pdo->fetchAll($sql, $params);
        return $rows ? $rows : [];
    }
    
    // 插入新用户
    public function insertUser($username, $password, $email, $status = '1'){
        $createdTime = date('Y-m-d H:i:s');
        
        $sql = "INSERT INTO $this->table (username, password, email, status, created_time) VALUES (:username, :password, :email, :status, :created_time)";
        
        $params = [
            ':username' => $username,
            ':password' => empty($password) ? '123456' : $password, // 默认密码
            ':email' => $email,
            ':status' => $status,
            ':created_time' => $createdTime
        ];
        
        return $this->pdo->exec($sql, $params);
    }
    
    // 更新用户登录信息（IP和登录时间）
    public function updateUserLoginInfo($username, $ip) {
        $lastLogin = date('Y-m-d H:i:s');
        
        $sql = "UPDATE $this->table SET ip = :ip, last_login = :last_login WHERE username = :username";
        
        $params = [
            ':ip' => $ip,
            ':last_login' => $lastLogin,
            ':username' => $username
        ];
        
        return $this->pdo->exec($sql, $params);
    }

}